<script setup>
import { onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useTokenStore } from "@/stores/token";
import useUserInfoStore from "@/stores/userInfo";
import { ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();
const tokenStore = useTokenStore();
const userInfoStore = useUserInfoStore();

// 全局token验证
const validateGlobalToken = async () => {
  // 如果是登录页面，不进行验证
  if (route.path === "/login") {
    return;
  }

  if (tokenStore.hasToken()) {
    try {
      const isValid = await tokenStore.validateToken();
      if (!isValid) {
        ElMessage.warning("登录已过期，请重新登录");
        userInfoStore.removeInfo();
        tokenStore.removeToken();
        router.push("/login");
      }
    } catch (error) {
      console.error("Token验证失败:", error);
      ElMessage.error("登录状态异常，请重新登录");
      userInfoStore.removeInfo();
      tokenStore.removeToken();
      router.push("/login");
    }
  }
};

onMounted(() => {
  validateGlobalToken();
});
</script>

<template>
  <router-view />
</template>

<style>
/* 全局样式 */
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif;
}

#app {
  height: 100%;
}
</style>
